
package me.module.toolMain
{
	import com.adobe.images.PNGEncoder;
	import com.zero.framework.interfaces.INotification;
	import com.zero.framework.interfaces.INotifyResponder;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import me.common.AppFacade;
	import me.common.Common;
	import me.common.GlobalCore;
	import me.common.res.GameLoader;
	import me.common.resource.ResType;
	import me.common.resource.Resource;
	import me.module.alert.Alert;
	import me.notification.MainNotification;
	import me.utils.NumberTool;
	import me.utils.OpenFile;
	import me.vo.ActionVO;
	
	
	/**
	 * @author 缺硒
	 */
	public class MainModel implements INotifyResponder
	{
		private static var __instance:MainModel;
		
		private var _count:int = 0;
		
		//原精灵的大小
		private var _preWidth:int = 160;
		private var _preHeight:int = 160;
		
		//精灵的大小
		private var _spriteWidth:int;
		private var _spriteHeight:int;
		
		private var _offsetX:Number;
		private var _offsetY:Number;
		
		private var _runPath:String;
		private var _waitPath:String;
		private var _dazuoPath:String;
		private var _spriteDic:Dictionary;
		
		private var _theABitmapdata:BitmapData;
		private var _theBBitmapdata:BitmapData;
		private var _actionList:Array;
		private var _rootFile:File;
		
		private var _totalCount:int = 0;
		
		private var _fucking1:ByteArray;
		private var _fucking2:ByteArray;
		private var _fucking3:ByteArray;
		private var _fucking4:ByteArray;
		//判断是否没行数
		private var _isWithoutLineNum:Boolean = false;
		
		private var _isHaveBack:Boolean = true;
		
		public static function getInstance():MainModel
		{
			if(__instance == null)
				__instance = new MainModel(new Singleton());
			return __instance;
		}
		
		// 构造函数
		public function MainModel(s:Singleton)
		{
			AppFacade.getInstance().registerResponder(this);
			
			
		}
		
		
		
		public function get notificationList():Array
		{
			return [
				MainNotification.UI_CLICK_FIND_PATH,
				MainNotification.UI_SET_SPRITE_SIZE,
				MainNotification.UI_OUT_PUT
			];
		}
		
		public function notifyHandler(notification:INotification):void
		{
			var body:Object = notification.getBody();
			switch(notification.getName())
			{
				case MainNotification.UI_CLICK_FIND_PATH:
					OpenFile.browseForDirectory(onc);
					break;
				
				case MainNotification.UI_SET_SPRITE_SIZE:
					_spriteWidth 	= body.w;
					_spriteHeight 	= body.h;
					break;
				
				case MainNotification.UI_OUT_PUT:
					onOutPut(body);
					break;
			}
		}
		
		private function onOutPut(data:Object):void
		{
			_offsetX 		= data.x;
			_offsetY 		= data.y;
			_spriteWidth 	= data.w;
			_spriteHeight	= data.h;
			
			stickASprites();
			var ba:ByteArray = PNGEncoder.encode(_theABitmapdata);
			var file:File = _rootFile.resolvePath("..");
			var fileStream:FileStream = new FileStream();
			fileStream.open(file.resolvePath(GlobalCore.avatarName+".png"), FileMode.WRITE);
			fileStream.writeBytes(ba, 0, ba.length);
			fileStream.close();
		}
		
		private function onc(file:File):void
		{
			_actionList = new Array();
			_isWithoutLineNum = false;
			Resource.getInstance().clearAll();
			GlobalCore.frameNum = 0;
			GlobalCore.totleLine = 0;
			_totalCount = 0;
			if(file != null)
			{
				Alert.showLog("开始载入......");
				_rootFile = file;
				var files:Array =  file.getDirectoryListing();
				for(var i:int = 0; i < files.length; i ++)
				{
					var path:String = files[i].name;
					var strs:Array = path.split("_");
					if(strs.length == 2)
					{
						GlobalCore.avatarName 	= strs[0];
						var action:ActionVO 	= new ActionVO();
						action.name 	= strs[1];
						action.urlPath 	= files[i].nativePath;
						_actionList.push(action);
						//判断文件夹名_后面叫什么名
						//						if(strs[1] == "run01")
						//							_runPath = files[i].nativePath;
						//						if(strs[1] == "stand01")
						//							_waitPath = files[i].nativePath;
						//						if(strs[1] == "dazuo01")
						//							_dazuoPath = files[i].nativePath;
					}
				}
				//				trace(GlobalCore.avatarName, _runPath, _waitPath, _dazuoPath)
				//				loadRunSprites();
				if(GlobalCore.isNpc == false)
					_actionList.reverse();
				analyzeAction();
			}
		}
		
		private function analyzeAction():void
		{
			if(_totalCount < _actionList.length)
			{
				var action:ActionVO = _actionList[_totalCount];
				var partPath:String =  GlobalCore.avatarName + "_" + action.name;
				var files:Array = _rootFile.resolvePath(partPath).getDirectoryListing();
				for(var i:int = 0; i < files.length; i ++)
				{
					var file:File = files[i] as File;
					var strs:Array = file.name.split(".");
					if(strs.length == 2 && strs[1] == "png")
					{
						strs = strs[0].split("_");
						if(strs.length == 4)
						{
							if(int(strs[2]) > action.lineNum) action.lineNum = int(strs[2]);
							if(int(strs[3]) > action.frameNum) action.frameNum = int(strs[3]);
							if(action.frameNum > GlobalCore.frameNum) GlobalCore.frameNum = action.frameNum;
						}
						else if(strs.length == 3)
						{
							action.lineNum = 1;
							if(int(strs[2]) > action.frameNum) action.frameNum = int(strs[2]);
							if(action.frameNum > GlobalCore.frameNum) GlobalCore.frameNum = action.frameNum;
							_isWithoutLineNum = true;
						}
					}
				}
				
				for(i = 0; i < action.lineNum; i ++)
				{
					for(var j:int = 0; j < action.frameNum; j ++)
					{
						if(_isWithoutLineNum)
						{
							var url:String = action.urlPath + "\\" + GlobalCore.avatarName + "_" + action.name + "_" + NumberTool.upperZero(j+1) + ".png";
							Resource.getInstance().appendMultiRes(action.name + i + "," + j, ResType.IMG, url);
						}
						else
						{
							url = action.urlPath + "\\" + GlobalCore.avatarName + "_" + action.name + "_" + (i+1)+ "_" + NumberTool.upperZero(j+1) + ".png";
							Resource.getInstance().appendMultiRes(action.name + i + "," + j, ResType.IMG, url);
						}
					}
				}
				GlobalCore.totleLine += action.lineNum;
				Resource.getInstance().startLoad(onActionLoaded);
				//
			}
			else
			{
				loadSpriteAllOk();
			}
			
		}
		
		/**
		 * 一个动作加载完成 
		 */		
		private function onActionLoaded():void
		{
			Alert.showLog(_actionList[_totalCount].name+"  加载完成");
			_totalCount ++;
			analyzeAction();
		}
		
		/**
		 * 所有帧加载完成 
		 */		
		private function loadSpriteAllOk():void
		{
			_spriteDic = Resource.getInstance().resList;
			_preWidth　	= _spriteDic[_actionList[0].name + "0,0"].width;
			_preHeight	= _spriteDic[_actionList[0].name + "0,0"].height;
			
			_spriteWidth	= _preWidth;
			_spriteHeight	= _preHeight;
			
			GlobalCore.spritePreH 	= _preHeight;
			GlobalCore.spritePreW 	= _preWidth;
			GlobalCore.spriteDic 	= _spriteDic;
			GlobalCore.actions = _actionList;
			
			AppFacade.getInstance().sendNotification(MainNotification.TO_SHOW_ACTION_SPRITE);
			Alert.hideLog();
		}
		
		/**
		 * 把所有帧粘贴成一张bitmapdata 
		 */		
		private function stickASprites():void
		{
			trace(_spriteWidth * GlobalCore.frameNum, _spriteHeight * GlobalCore.totleLine);
			_theABitmapdata = new BitmapData(_spriteWidth * GlobalCore.frameNum, _spriteHeight * GlobalCore.totleLine, true, 0x000000);
			
			var lineNum:int = 0;
			for(var i:int = 0; i < _actionList.length; i ++)
			{
				var action:ActionVO = _actionList[i];
				for(var j:int = 0; j < action.lineNum; j ++)
				{
					for(var k:int = 0; k < GlobalCore.frameNum; k ++)
					{
						var srcBmd:BitmapData = Resource.getInstance().resList[action.name + j + "," + k];
						var newBmd:BitmapData = new BitmapData(_spriteWidth, _spriteHeight,true,0x000000);
						   
						//宽度变化造成的位图位移量
						var sizeOffX:int = (GlobalCore.spritePreW - _spriteWidth)/2;
						var sizeOffY:int = (GlobalCore.spritePreH - _spriteHeight)/2;
						
						newBmd.copyPixels(srcBmd, new Rectangle(sizeOffX- _offsetX,sizeOffY - _offsetY, _spriteWidth, _spriteHeight),
							new Point(0, 0)); //单张帧的切割
						
						_theABitmapdata.copyPixels(newBmd, newBmd.rect, 
							new Point(k*_spriteWidth, lineNum *_spriteHeight), null, null, true);
					}
					lineNum ++;
				}
				//
			}
			trace(lineNum, GlobalCore.totleLine)	
		}
		//
	}
}

class Singleton {}